package com.cheung.leetcode.str;

import java.util.Arrays;

public class LC43 {

    public static String multiply(String num1, String num2) {
        if ("0".equals(num1) || "0".equals(num2)) {
            return "0";
        }
        String sb = "";

        int i = num1.length() - 1;
        while (i >= 0) {
            int x = num1.charAt(i) - '0';
            String sub = time(num2, x);
            // 补零
            sub += "0".repeat(num1.length() - 1 - i);
            sb = addStrings(sub, sb);
            i--;
        }

        return sb;
    }

    public static String time(String num1, int x) {
        StringBuilder sb = new StringBuilder();
        int add = 0;
        int j = num1.length() - 1;
        while (j >= 0 || add != 0) {
            int y = j >= 0 ? num1.charAt(j) - '0' : 0;
            sb.append((y * x + add) % 10);
            add = (y * x + add) / 10;
            j--;
        }
        return sb.reverse().toString();
    }


    public static String addStrings(String num1, String num2) {

        StringBuilder sb = new StringBuilder();
        int add = 0;
        int i = num1.length() - 1;
        int j = num2.length() - 1;
        while (i >= 0 || j >= 0 || add != 0) {
            int i1 = i >= 0 ? num1.charAt(i) - '0' : 0;
            int i2 = j >= 0 ? num2.charAt(j) - '0' : 0;
            sb.append((i1 + i2 + add) % 10);
            add = (i1 + i2 + add) / 10;
            i--;
            j--;
        }

        return sb.reverse().toString();
    }


    // leetcode解法
    public static String multiplyV2(String num1, String num2) {
        if ("0".equals(num1) || "0".equals(num2)) {
            return "0";
        }

        int[] ans = new int[num1.length() + num2.length()];
        for (int i = 0; i < num1.length(); i++) {
            int x = num1.charAt(i) - '0';
            for (int j = 0; j < num2.length(); j++) {
                int y = num2.charAt(j) - '0';
                ans[i + j + 1] += x * y;
            }
        }
        System.out.println(Arrays.toString(ans));
        // 将ans数组转换成每个数只有一位数
        int i = ans.length - 1;
        while (i >= 1) {
            ans[i - 1] += ans[i] / 10;
            ans[i] %= 10;
            i--;
        }

        StringBuilder sb = new StringBuilder();
        // 判断第一位是否为0
        if (ans[0] != 0) {
            sb.append(ans[0]);
        }
        // 将数组拼接起来
        for (int j = 1; j < ans.length; j++) {
            sb.append(ans[j]);
        }
        return sb.toString();
    }


    public static void main(String[] args) {

        System.out.println(multiplyV2("20", "0"));
        System.out.println(20 * 0);

    }
}
